package edu.zac.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

import java.util.Arrays;

/**
 * @Title
 * @Author Peihan.Zhang
 * @Email zhangpeihan@sjgtw.com
 * @Date 2021/10/22 15:11
 * @Versions 1.0
 */

@Component
@Aspect
public class SpringAop {


    @Pointcut("@annotation(edu.zac.anno.Cache)")
    public void pointcut(){

    }

   @Before("pointcut()")
    public void before(JoinPoint joinPoint){
       System.out.println("获取目标对象的属性"+joinPoint.getTarget().getClass());
       System.out.println(""+joinPoint.getSignature().getDeclaringTypeName());
       System.out.println(""+joinPoint.getSignature().getName());
       System.out.println(""+ Arrays.toString(joinPoint.getArgs()));
        System.out.println("方法执行之前");
    }

    @AfterReturning(pointcut ="pointcut()",returning = "result")
    public void afterReturning(JoinPoint joinPoint, Object result){
        System.out.println("方法之后执行了");
        System.out.println("该方法的返回值是"+result);
    }

    @AfterThrowing("pointcut()")
    public void afterThrowing(){
        System.out.println("异常的方法执行了");
    }

    @AfterThrowing(pointcut = "@annotation(edu.zac.anno.Cache)",throwing = "e")
    public void afterthow(JoinPoint joinPoint,Exception e){

        System.out.println(joinPoint.getTarget().getClass());
        System.out.println(e.getMessage());

    }

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint proceedingJoinPoint){
        Object  data =null;
        System.out.println("事务开始");
        try {
           data= proceedingJoinPoint.proceed();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        System.out.println("事务结束");
        return  data;
    }

}
